package com.overtime.expense.controller;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import com.base.bean.Position;
import com.base.bean.RespBean;
import com.base.bean.User;
import com.common.UserUtils;
import com.overtime.account.service.AccountTableService;
import com.overtime.application.bean.ApplicationResult;
import com.overtime.application.service.ApplicationResultService;
import com.overtime.project.bean.ProjectManage;
import com.overtime.project.service.ProjectService;
import org.apache.poi.hssf.usermodel.*;

import java.awt.*;
import java.io.FileOutputStream;

import com.overtime.expense.bean.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.overtime.expense.service.ExpenseService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.common.UserUtils.getCurrentHr;

@RestController
public class ExpenseController {
    @Autowired
    ExpenseService expenseService;
    Expense expense;
    @Autowired
    AccountTableService accountTableService;
    @Autowired
    private ApplicationResultService applicationResultService;
    @Autowired
    ProjectService projectService;

    /*使用PageHelper分页查询*/
    /*@RequestMapping(value = "/expense/control", method = RequestMethod.POST)
    public Map<String, Object> proInfo(int currentPage,int pageSize){
        List<Expense> list = expenseService.getAllInfo(currentPage,pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        int total =expenseService.getTotal();
        map.put("list", list);
        map.put("number", total);
        return map;
    }*/

    public static final float PXTOPT = 0.75f;
    public static final int PERCENT_WIDTH = 50;
    public static final int PERCENT_HEIGHT = 20;

    //获取报销单表格数据
    @RequestMapping(value = "/expense/control", method = RequestMethod.POST)
    public List<Expense> proInfo(String project_id,String start_time,String end_time,Integer audit_status,Integer[] position_id) {
        Map<String, Object> param = new HashMap<>();
        param.put("project_id", project_id);
        param.put("start_time", start_time);
        param.put("end_time", end_time);
        param.put("audit_status",audit_status);
        if(position_id.length==0){
            param.put("position_id",null);
        }else{
            param.put("position_id",position_id);
        }

        return expenseService.getAllInfo(param);
    }

    //获取弹框下拉框的相关人员名称ID
    @RequestMapping(value = "/expense/getexusername", method = RequestMethod.POST)
    public List<Expense> getExUserName(Expense expense) {
        return expenseService.getExUserName(expense);
    }

    //获取职位信息
    @RequestMapping(value = "/expense/getPosition", method = RequestMethod.GET)
    public List<Position> getPosition(){

        return expenseService.getPosition();
    }

    //获取单条数据
    @RequestMapping(value = "/expense/getById", method = RequestMethod.POST)
    public List<Expense> getExpenseById(Expense expense) {
        Long id = UserUtils.getCurrentHr().getId();
        expense.setUser_id(id.intValue());
        return expenseService.getExpenseById(expense);
    }

    @RequestMapping(value = "/expense/manage/dialogappli", method = RequestMethod.GET)
    public List<Expense> getAppliId() {
        //获取申请表ID
        return expenseService.getAppliId();
    }

    @RequestMapping(value = "/expense/manage/dialogappli1", method = RequestMethod.GET)
    public List<Expense> getAppliId1() {
        //获取申请表ID
        return expenseService.getAppliId1();
    }

    @RequestMapping(value = "/expense/manage/aduname", method = RequestMethod.GET)
    public List<Expense> getAduName() {
        //获取负责人名称
        return expenseService.getAduName();
    }

    @RequestMapping(value = "/expense/manage/exstu", method = RequestMethod.GET)
    public List<Expense> getExStu() {
        //获取审核状态
        return expenseService.getExStu();
    }

    @RequestMapping(value = "/expense/manage/dialogproid", method = RequestMethod.GET)
    public List<ProjectBean> getProId() {
        return expenseService.getProId();
    }

    //获取部门下拉框数据
    @RequestMapping(value = "/expense/manage/deptid", method = RequestMethod.GET)
    public List<ProjectManage> getDeptIdPro() {
        return expenseService.getDeptIdPro();
    }

    @RequestMapping("/expense/getProjectDataByTime")
    public List<Map> getProjectDataByTime(String depno, String starttime, String endtime, String project_number,int[] positionid) {
        List<Map> list = expenseService.getProjectDataByTime(depno, starttime, endtime, project_number,positionid);
        return list;
    }
    @RequestMapping("/expense/getProjectDataByExpenseId")
    public List<Map> getProjectDataByExpenseId(int[] expense_ids) {
        List<Map> list = expenseService.getProjectDataByExpenseId(expense_ids);
        return list;
    }
    @RequestMapping(value = "/expense/manage/extype", method = RequestMethod.GET)
    public List<Expense> getExType() {
        //获取项目相关
        return expenseService.getExType();
    }

    //获取统计图下拉框数据
    @RequestMapping(value = "/expense/userdata", method = RequestMethod.GET)
    public List<Expense> getUserData() {
        //获取申请表ID
        return expenseService.getUserData();
    }

    //根据项目名称查询相关
    @RequestMapping(value = "/expense/manage/select", method = RequestMethod.POST)
    public Map<String, Object> getNewData(Expense expense, String end_time, String start_time) {
        if ("".equals(start_time)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            end_time = simpleDateFormat.format(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date); // 设置为当前时间
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
            date = calendar.getTime();
            start_time = simpleDateFormat.format(date);
        }
        Map<String, Object> map = expenseService.getNewData(expense, end_time, start_time);
        return map;
    }

    //获取加班人员明细表的数据
    @RequestMapping(value = "/expense/detailtab", method = RequestMethod.POST)
    public Map<String, Object> getDetailTable(Expense expense, String start_time, String end_time,int[] positionid) {
        if ("".equals(start_time)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            end_time = simpleDateFormat.format(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date); // 设置为当前时间
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
            date = calendar.getTime();
            start_time = simpleDateFormat.format(date);
        }
        Map<String, Object> map = expenseService.getDetailTable(expense, start_time, end_time,positionid);
        return map;
    }

    @RequestMapping(value = "/expense/detailtabByExpenseIds", method = RequestMethod.POST)
    public Map<String, Object> detailtabByExpenseIds(int[] expense_ids) {

        Map<String, Object> map = expenseService.getDetailTableByExpenseIds(expense_ids);
        return map;
    }
    //获取当前登陆者的姓名以及对应ID
    @RequestMapping(value = "/expense/getloginuser", method = RequestMethod.POST)
    public Map<String, Object> getLoginUser() {
        Map<String, Object> map = expenseService.getLoginUser();
        return map;
    }

    //编辑报销单的审核状态
    @RequestMapping(value = "/expense/auditbyid", method = RequestMethod.POST)
    public ResultBean auditById(Expense expense, String username) {
        int result = expenseService.auditById(expense, username);
        if (result == 1) {
            return new ResultBean("success", "审核成功!");
        }
        return new ResultBean("error", "审核失败!");
    }

    //编辑报销单
    @RequestMapping(value = "/expense/manage/editex", method = RequestMethod.POST)
    public ResultBean updateProById(Expense expense) {
        int result = expenseService.updateExById(expense);
        int total = expenseService.selectBeforeUpdate1(expense);
        List<Expense> list = expenseService.getExpenseById(expense);
        Expense resultExpense = list.get(0);
        int i=0;
        //餐费判断
        if(resultExpense.getEatMoney()==0&&expense.getEatMoney()!=0){//数据库中不为0修改后不为0则新增
            i=expenseService.addExpenseFee1(expense.getEatMoney(),expense.getExpense_id());
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getEatMoney()!=0&&expense.getEatMoney()==0){//数据库中不为0,即有这条数据则修改,若修改为0则删除该数据
            i=expenseService.deleteExpenseFee1(expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getEatMoney()!=0&&expense.getEatMoney()!=0){//数据库中不为0,即有这条数据则修改,若修改不为0则修改该数据
            i=expenseService.updateExpenseFee1(expense.getEatMoney(),expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }
        //交通费判断
        if(resultExpense.getTrafficMoney()==0&&expense.getTrafficMoney()!=0){//数据库中不为0修改后不为0则新增
            i=expenseService.addExpenseFee2(expense.getTrafficMoney(),expense.getExpense_id());
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getTrafficMoney()!=0&&expense.getTrafficMoney()==0){//数据库中不为0,即有这条数据则修改,若修改为0则删除该数据
            i=expenseService.deleteExpenseFee2(expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getTrafficMoney()!=0&&expense.getTrafficMoney()!=0){//数据库中不为0,即有这条数据则修改,若修改不为0则修改该数据
            i=expenseService.updateExpenseFee2(expense.getTrafficMoney(),expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
    }
        //补助判断
        if(resultExpense.getExtraMoney()==0&&expense.getExtraMoney()!=0){//数据库中不为0修改后不为0则新增
            i=expenseService.addExpenseFee3(expense.getExtraMoney(),expense.getExpense_id());
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getExtraMoney()!=0&&expense.getExtraMoney()==0){//数据库中不为0,即有这条数据则修改,若修改为0则删除该数据
            i=expenseService.deleteExpenseFee3(expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getExtraMoney()!=0&&expense.getExtraMoney()!=0){//数据库中不为0,即有这条数据则修改,若修改不为0则修改该数据
            i=expenseService.updateExpenseFee3(expense.getExtraMoney(),expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }
        //其他费用判断
        if(resultExpense.getElseMoney()==0&&expense.getElseMoney()!=0){//数据库中不为0修改后不为0则新增
            i=expenseService.addExpenseFee4(expense.getElseMoney(),expense.getExpense_id());
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getElseMoney()!=0&&expense.getElseMoney()==0){//数据库中不为0,即有这条数据则修改,若修改为0则删除该数据
            i=expenseService.deleteExpenseFee4(expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }else if(resultExpense.getElseMoney()!=0&&expense.getElseMoney()!=0){//数据库中不为0,即有这条数据则修改,若修改不为0则修改该数据
            i=expenseService.updateExpenseFee4(expense.getElseMoney(),expense);
            if(i!=1){
                return new ResultBean("error","修改失败");
            }
        }


        return  new ResultBean("success","更新成功");
    }

    //新增报销单
    @RequestMapping(value = "/expense/manage/addex", method = RequestMethod.POST)
    public ResultBean addExpense(String[] application_ids,ExpensePo expense) {
        //新增报销单表数据
        for(String application_id:application_ids){
            expense.setApplication_id(Integer.parseInt(application_id));
            ApplicationResult applicationResult = applicationResultService.queryResultById(Integer.parseInt(application_id));
            Date start = applicationResult.getResult_start_time();
            Date end = applicationResult.getResult_end_time();
            Calendar startCalendar = Calendar.getInstance();
            double money = 0.0;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
            startCalendar.setTime(start);
            while(start.getTime()<=end.getTime()){
                expense.setApplication_date(start);
                //判断是否为节假日加班
                Map map = new HashMap();
                map.put("time",startCalendar.getTime());
                List<Map> maps = expenseService.getTime(map);
                if(startCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || startCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY||!maps.isEmpty()){
                    expense.setDate_type(2);
                }else{
                    expense.setDate_type(1);

                }
                startCalendar.add(Calendar.DAY_OF_MONTH, 1);
                start = startCalendar.getTime();
                int result = expenseService.addExpense(expense);
                int id = expense.getExpense_id();
                if(expense.getDate_type()==1){
                    expenseService.addExpenseFee3(20.0,id);
                }else if(expense.getDate_type()==2){
                    expenseService.addExpenseFee3(100.0,id);
                }

            }
        }


        /*if (result == 1) {
            //新增各项费用
            if (eat_money != 0) {
                int result1 = expenseService.addExpenseFee1(eat_money, id);
                if (result1 == 1) {
                    if (traffic_money != 0) {
                        int result2 = expenseService.addExpenseFee2(traffic_money, id);
                        if (result2 == 1) {
                            if (extra_money != 0) {
                                int result3 = expenseService.addExpenseFee3(extra_money, id);
                                if (result3 == 1) {
                                    if (else_money != 0) {
                                        int result4 = expenseService.addExpenseFee4(else_money, id);
                                        if (result4 == 1) {
                                            return new ResultBean("success", "添加成功!");
                                        }
                                    }
                                    return new ResultBean("success", "添加成功!");
                                }
                                return new ResultBean("success", "添加成功!");
                            }
                        }
                        return new ResultBean("success", "添加成功!");
                    }
                }
                return new ResultBean("success", "添加成功!");
            }
            return new ResultBean("success", "添加成功!");
        }*/
        return new ResultBean("success", "添加成功!");
    }


    //删除单/多条报销单
    @RequestMapping("/expense/manage/del/{pids}")
    public ResultBean deletePosById(@PathVariable String pids) {
        if (expenseService.deleteExById(pids)) {

            if (expenseService.deleteExFeeById(pids)) {
                return new ResultBean("success", "删除成功!");
            }
            return new ResultBean("success", "删除成功!");
        }
        return new ResultBean("error", "删除失败!");
    }

    //统计图
    @RequestMapping(value = "/expense/chart", method = RequestMethod.POST)
    public List<Chart> getChart(String mouth, String year, String user_id) {

        List<Chart> list = expenseService.getChart(mouth, year, user_id);

        return list;
    }

    //饼图统计图
    @RequestMapping(value = "/expense/pie", method = RequestMethod.POST)
    public List<Chart> getPie(String mouth, String year, String user_id) {
        List<Chart> list = expenseService.getPie(mouth, year, user_id);

        return list;
    }

    @RequestMapping("/expense/download")
    public void excelDownload(HttpServletResponse response, int depno, String starttime, String endtime, Expense expense) throws IOException {
        /* System.out.println(depno);*/
        /* List list = accountTableService.getMoney(depno,starttime,endtime);*/
        /* List userList = accountTableService.getUser(depno);*/
        /*   List<Expense> userList =expenseService.getTableColumn(expense);*/


        ExportExcel exportExcel = new ExportExcel();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("line");

        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(77 * PXTOPT);

        final String text = "日期\n\n\n        金额\n\n\n\n\n\n         人员";
        HSSFCell cell = row.createCell(0);
        HSSFCellStyle cellStyle = exportExcel.getCellFormat(wb);
        int x1 = 61, y1 = 77;
        int x2 = 144, y2 = 39;
        /*int x3 = 144, y3 = 31;*/
        int[] xys = {x1, y1, x2, y2};
        exportExcel.drawLine(sheet, row, 0, 0, 144, 77, xys);
        cell.setCellValue(text);
        cell.setCellStyle(cellStyle);

        //从此处-209行 自定义表格内容  方法：setCellValue
        cell = row.createCell(1);
        cell.setCellStyle(cellStyle);
        //表头用户名
   /*     for(int u=2;u<userList.size();u++){
            cell = row.createCell(u);
            cell.setCellStyle(cellStyle);
           *//* userList.get(expense.getName());*//*
         *//*Object user = userList.get(u);
            String userName =(String) user;
               cell.setCellValue(userName);*//*
        }*/

        /*cell = row.createCell(2);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("400");

        cell = row.createCell(3);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("500");*/

        /*row = sheet.createRow(1);
        row.setHeightInPoints(83 * PXTOPT);
        cell = row.createCell(0);
        cell.setCellStyle(cellStyle);

        cell = row.createCell(1);
        cell.setCellStyle(cellStyle);

        cell = row.createCell(2);
        cell.setCellStyle(cellStyle);

        cell = row.createCell(3);
        cell.setCellStyle(cellStyle);*/


        try {
            /* FileOutputStream fos = new FileOutputStream("D:/line.xls");*/
            wb.write(os);
        } catch (Exception e) {


        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(("报销金额表" + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }

    }

    @RequestMapping("/expense/audit")
    public RespBean audit(int[] ids, String expCom) {
        return expenseService.audit(ids, expCom);
    }

    @RequestMapping("/expense/callback")
    public RespBean callback(int[] ids, String expCom) {
        return expenseService.callback(ids,expCom);
    }

    @RequestMapping("/expense/isAuditor")
    public boolean isAuditor() {
        return expenseService.isAuditor();
    }

    @RequestMapping("/expense/getProjectData")
    public List<ProjectManage> getProjectData(String depno) {
        return projectService.getProjectData(depno);
    }

}
